#include "main.h"
int main(int argc, char ** argv){
	if (argc<3)
		die ("Usage: dnsClient domeniu tip_query\n");
	int sd, rc, tip = 1;
	struct sockaddr_in remoteServAddr;
	FILE *f = fopen(SERVER_FILE,"r");
	char* domain = argv[1];
	char* type = argv[2];
	int opcode = 0;
	if (strcmp(type,"PTR") == 0){
		tip = 12;
		char* d = (char*)mycalloc(50, sizeof(char));
		int a[4];
		a[0] = atoi(strtok(domain, "."));
		a[1] = atoi(strtok(NULL,"."));
		a[2] = atoi(strtok(NULL,"."));
		a[3] = atoi(strtok(NULL,"."));
		sprintf(d,"%d.%d.%d.%d",a[3], a[2], a[1], a[0]); 
		memcpy(d+strlen(d), ".IN-ADDR.ARPA",13);
		domain = d; 
	}
	
	char* line = (char*)mycalloc(1024, sizeof(char));
	if (strcmp(type,"SOA") == 0)
		tip = 6;
	if (strcmp(type,"A") == 0)
		tip = 1;
	if (strcmp(type,"NS") == 0)
		tip = 2;
	if (strcmp(type, "MX") == 0)
		tip = 15;
	if (strcmp(type, "PTR") == 0)
		tip = 12;
	while (fgets(line, 100, f)!=0){
		line[strlen(line) - 1] = 0;
		//printf("%s\n", line);
		if (line[0]!='#' && strlen(line)>4){
			conectare(line, &sd, &rc, &remoteServAddr);
			sendPacket(newQuery(1, opcode, domain, tip, 1), sd, &remoteServAddr);			
			init_alarm();
			was_timeout=set_alarm(2);
			printResponse(receivePacket(sd), domain);
			if (!*was_timeout){
				exit(0);
			}
			cancel_alarm();
			cleanup_alarm();
		}		
		memset(line, 0, 1024);
	}	
	return 0;
}
